package com.wangsd.my_more_database.common.datasource;


import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

//@SpringBootConfiguration
//@MapperScan(basePackages = "com.wangsd.my_more_database.test1")
public class BasicDatasourceConfig {


    @Bean
    @Primary //默认数据源
    @ConfigurationProperties(prefix = "spring.datasource.test1") //将properties中以mysql为前缀的参数值，写入方法返回的对象中
    public DataSource basicDataSource() {
        //通过DataSourceBuilder构建数据源
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean
    @Primary //默认事务
    public SqlSessionFactory basicSqlSessionFactory(DataSource basicDataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(basicDataSource);
        return bean.getObject();
    }

    /**
     * 事务管理
     *
     * @param basicDataSource
     * @return
     */
    @Bean
    @Primary
    public DataSourceTransactionManager basicTransactionManager(DataSource basicDataSource) {
        return new DataSourceTransactionManager(basicDataSource);
    }
}
